﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using WF.Common;
using Com.DAO;

namespace WF.Web.Components.WorkSpace
{
    public partial class OutOfOfficeEdit : BaseUserControl
    {
        protected string itemID = null;
        private string viewOpNo = "002.007.OP02"; //设置委托
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!this.CheckPersonalRight(viewOpNo))
            //{
            //    this.ShowWarningMessage("无此操作权限！");
            //    return;
            //}

            if(this.CmdType == "ADD")
            {
                this.itemID = System.Guid.NewGuid().ToString();
                this.txtADUserID.ReadOnly = false;
            }

            if (this.CmdType == "MOD")
            {
                this.itemID = Request.QueryString["ItemID"];
            }

            if (!IsPostBack)
            {
                LoadData(this.itemID);
            }

            this.SetSubmitButton(btnSubmit, true, true);
        }

        protected void dgList_CancelCommand(object source, DataGridCommandEventArgs e)
        {
            this.dgList.EditItemIndex = -1;
            this.dgList.DataBind();

        }

        protected void dgList_EditCommand(object source, DataGridCommandEventArgs e)
        {
            this.dgList.EditItemIndex = e.Item.ItemIndex;
            this.dgList.DataBind();
        }

        protected void dgList_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                DataSet ds = (DataSet)Session["OutOfOfficeSetDataSet"];
                if (e.CommandName == "AddNewRow")
                {
                    dgList.Columns[4].Visible = false;
                    DataRow dr = ds.Tables[0].NewRow();
                    dr["DataID"] = CentaUtil.GetNewGUID();
                    dr["ItemID"] = this.itemID;
                    dr["ForwardEmpID"] = "";
                    dr["ForwardADUserID"] = "";
                    dr["ForwardEmpName"] = "";
                    dr["ForwardDeptID"] = "";

                    ds.Tables[0].Rows.Add(dr);

                    this.dgList.DataSource = ds.Tables[0].DefaultView;
                    this.dgList.DataBind();

                    int current = dgList.Items.Count - 1;
                }

                if (e.CommandName == "Edit" || e.CommandName == "Cancel")
                {

                    this.dgList.DataSource = ds.Tables[0].DefaultView;
                    this.dgList.DataBind();

                    if (e.CommandName == "Edit")
                    {
                        SetSubmitButtonState(false);
                        dgList.Columns[4].Visible = false;
                    }

                    if (e.CommandName == "Cancel")
                    {
                        SetSubmitButtonState(true);
                        dgList.Columns[4].Visible = true;
                    }

                }

                if (e.CommandName == "Delete")
                {
                    ds.Tables[0].Rows[e.Item.ItemIndex].Delete();
                    ds.Tables[0].AcceptChanges();
                    this.dgList.DataSource = ds.Tables[0].DefaultView;
                    this.dgList.DataBind();

                }

                Session["OutOfOfficeSetDataSet"] = ds;

            }
            catch (Exception ex)
            {
                CentaUtil.SendExceptionMessage(this, ex);
                throw ex;
            }
        }

        protected void dgList_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            int current = e.Item.ItemIndex;
            DataSet ds = (DataSet)Session["OutOfOfficeSetDataSet"];
            foreach (DataGridItem item in this.dgList.Items)
            {
                if (item.ItemIndex == current)
                {

                    string aduserID = ((TextBox)item.Cells[1].FindControl("txtForwardAdUserID")).Text;
                    string empID, empName, deptID;
                    if (CheckK3UserID(this.updateGrid, aduserID, out empID, out empName, out deptID))
                    {
                        ds.Tables[0].Rows[current]["ForwardADUserID"] = aduserID;
                        ds.Tables[0].Rows[current]["ForwardEmpName"] = empName;
                        ds.Tables[0].Rows[current]["ForwardEmpID"] = empID;
                        ds.Tables[0].Rows[current]["ForwardDeptID"] = deptID;
                    }
                    else
                    {


                        ds.Tables[0].Rows[current]["ForwardADUserID"] = "";
                        ds.Tables[0].Rows[current]["ForwardEmpName"] = "";
                        ds.Tables[0].Rows[current]["ForwardEmpID"] = "";
                        ds.Tables[0].Rows[current]["ForwardDeptID"] = "";

                    }
                }
            }

            this.dgList.DataSource = ds.Tables[0].DefaultView;
            this.dgList.DataBind();
            Session["OutOfOfficeSetDataSet"] = ds;

            this.dgList.EditItemIndex = -1;
            this.dgList.DataBind();

            SetSubmitButtonState(true);
            dgList.Columns[4].Visible = true;

        }


        protected void SetSubmitButtonState(bool bEnabled)
        {
            this.btnSubmit.Enabled = bEnabled;

        }

        protected void LoadData(string itemID)
        {
            BusinessEntiry load = new BusinessEntiry(this.DataManager, "VW_WF_OutOfOfficeSet", "ItemID");
            if (load.OpenByKeyValue(itemID))
            {
                txtADUserID.Text = load.GetPropertyValue("ADUserID");
                rblState.SelectedValue = load.GetPropertyValue("Type");
                txtStartDate.Text = load.GetPropertyValue("StartDate") == "" ? "" : DateTime.Parse(load.GetPropertyValue("StartDate")).ToString("yyyy-MM-dd");
                txtEndDate.Text = load.GetPropertyValue("EndDate") == "" ? "" : DateTime.Parse(load.GetPropertyValue("EndDate")).ToString("yyyy-MM-dd");

            }

            string sql = string.Format(@" Select ItemID,DataID,EmpID,ForwardEmpID,ForwardADUserID,ForwardEmpName, '' As ForwardDeptID From VW_WF_OutOfOfficeSetDetail Where ItemID = '{0}'", itemID);
            DataSet ds = new DataSet();
            ds = this.DataManager.SelectDataSet(sql);
            this.dgList.DataSource = ds.Tables[0].DefaultView;
            this.dgList.DataBind();

            Session["OutOfOfficeSetDataSet"] = ds;
        }

        protected bool CheckADUserID(Control control, string adUserID, out string empID, out string empName)
        {
            BusinessEntiry data = new BusinessEntiry(this.DataManager, "Employee", "EmpID");
            if (data.Open(string.Format(@"DomainAccount ='{0}' And flagdeleted  = 0 and empstatus='在职' ", adUserID)))
            {
                empID = data.GetPropertyValue("EmpID");
                empName = data.GetPropertyValue("EmpName");
                return true;
            }
            else
            {
                empID = "";
                empName = "";
                this.AjaxShowMessage(control, "系统中无此用户！", true);
                return false;
            }
        }
        /// <summary>
        /// 从K3中检查被委托的人是否存在
        /// </summary>
        /// <param name="control"></param>
        /// <param name="adUserAccount"></param>
        /// <param name="empID"></param>
        /// <param name="empName"></param>
        /// <returns></returns>
        protected bool CheckK3UserID(Control control, string adUserAccount, out string empID, out string empName, out string deptID)
        {
            bool result = false;
            DataSet ds = null;
            try
            {
                SHZYK3.K3 probj = new SHZYK3.K3();
                ds = probj.GetEmpInfoByDomainAccount(adUserAccount);

                Com.Object.Fields fd = new Com.Object.Fields();
                fd.LoadDataFromDataSet(ds, true);
                empID = fd.GetFieldValue("EmpID").ToString();
                empName = fd.GetFieldValue("EmpName").ToString();
                deptID = fd.GetFieldValue("DeptID").ToString();
                result = true;
            }
            catch
            {
                empID = "";
                empName = "";
                deptID = "";
                this.AjaxShowMessage(control, "系统中无此用户！", true);
                result = false;
            }
            return result;
        }

        protected bool CheckOutOfOfficeEmpID(string empID, out string itemID)
        { 
            bool result = false;
            DataSet ds = null;
            string sql = "";
            itemID = "";
            sql = sql + "Select ItemID From WF_OutOfOfficeSet Where EmpID='" + empID + "'";
            ds = this.DataManager.SelectDataSet(sql);
            if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                itemID = ds.Tables[0].Rows[0]["ItemID"].ToString();
                result = true;
            }

            return result;
        }
        protected void SaveData()
        {
            //保存主表数据
            BusinessEntiry master = new BusinessEntiry(this.DataManager, "WF_OutOfOfficeSet", "ItemID");
            if (master.OpenByKeyValue(this.itemID))
            {
                master.SetProperty("Type", rblState.SelectedValue);
                master.SetProperty("StartDate", txtStartDate.Text.Trim() == "" ? null : txtStartDate.Text.Trim());
                master.SetProperty("EndDate", txtEndDate.Text.Trim() == "" ? null : txtEndDate.Text.Trim());
                master.SetProperty("ModDate", System.DateTime.Now.ToString());
                master.Save(!this.DataManager.IsBeginTrasaction);
            }


            if (rblState.SelectedValue == "OUT")
            {
                //保存明细数据
                this.DataManager.Execute(string.Format(@" Delete From WF_OutOfOfficeSetDetail Where ItemID = '{0}'", this.itemID));

                DataSet ds = (DataSet)Session["OutOfOfficeSetDataSet"];
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    BusinessEntiry save = new BusinessEntiry(this.DataManager, "WF_OutOfOfficeSetDetail", "DataID");
                    save.SetProperty("DataID", ds.Tables[0].Rows[i]["DataID"].ToString());
                    save.SetProperty("ItemID", this.itemID);
                    save.SetProperty("ForwardEmpID", ds.Tables[0].Rows[i]["ForwardEmpID"].ToString());
                    save.Save(!this.DataManager.IsBeginTrasaction);

                    //被委托的人如果在employee表中没有则保存,显示列表时查找用户的姓名及账号
                    BusinessEntiry emp = new BusinessEntiry(this.DataManager, "Employee", "EmpID");
                    string empID = ds.Tables[0].Rows[i]["ForwardEmpID"].ToString();
                    if (emp.OpenByKeyValue(empID))
                    {
                        emp.EntityStatus = Com.Data.EntityStatus.Update;
                    }
                    else
                    {
                        emp.EntityStatus = Com.Data.EntityStatus.New;
                    }
                    emp.SetProperty("EmpID", empID);
                    emp.SetProperty("EmpName", ds.Tables[0].Rows[i]["ForwardEmpName"].ToString());
                    emp.SetProperty("DomainAccount", ds.Tables[0].Rows[i]["ForwardADUserID"].ToString());
                    emp.SetProperty("DeptID", ds.Tables[0].Rows[i]["ForwardDeptID"].ToString());
                    emp.SetProperty("SyncTime", System.DateTime.Now.ToString());
                    emp.SetProperty("ModDate", System.DateTime.Now.ToString());
                    emp.Save(!this.DataManager.IsBeginTrasaction);

                }
            }
        }

        /// <summary>
        /// 设置委托
        /// </summary>
        protected void SetOutOfOffice()
        {
            DataSet ds = (DataSet)Session["OutOfOfficeSetDataSet"];
            WorkFlowHelper.SetUserOutOfOffice(WorkFlowHelper.GetK2ManagementServerConnectionString(), txtADUserID.Text.Trim(),
                    txtStartDate.Text.Trim(), txtEndDate.Text.Trim(), ds, rblState.SelectedValue);
        }

        /// <summary>
        /// 检查委托人数据
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        protected bool CheckDelegateData(Control control)
        {
            bool ret = true;
            if (rblState.SelectedValue == "OUT")
            {
                //如果设置了委托，但又没有设置委托人，需要提示
                DataSet ds = (DataSet)Session["OutOfOfficeSetDataSet"];
                if (ds.Tables[0].Rows.Count == 0)
                {
                    this.AjaxShowMessage(control, "必须指定委托人！", true);
                    return false;
                }


                if (ds.Tables[0].Select(string.Format(@" ForwardADUserID = '' ")).Length > 0)
                {
                    this.AjaxShowMessage(control, "被委托人不能为空！", true);
                    return false;
                }

                if (ds.Tables[0].Select(string.Format(@" ForwardADUserID = '{0}'", txtADUserID.Text.Trim())).Length > 0)
                {
                    this.AjaxShowMessage(control, "被委托人不能是委托人自身！", true);
                    return false;
                }
            }

            return ret;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //if (!CheckDelegateData(this.udateSubmit))
            //{
            //    return;
            //}
            try
            {
                if (this.CmdType == "ADD")
                {
                    try
                    {
                        DataSet ds = null;
                        SHZYK3.K3 probj = new SHZYK3.K3();
                        ds = probj.GetEmpInfoByDomainAccount(this.txtADUserID.Text);
                        Com.Object.Fields fd = new Com.Object.Fields();
                        fd.LoadDataFromDataSet(ds, true);
                        string empID = fd.GetFieldValue("EmpID").ToString();
                        string empName = fd.GetFieldValue("EmpName").ToString();
                        string deptID = fd.GetFieldValue("DeptID").ToString();

                        //被委托的人如果在employee表中没有则保存,显示列表时查找用户的姓名及账号
                        BusinessEntiry emp = new BusinessEntiry(this.DataManager, "Employee", "EmpID");
                        if (emp.OpenByKeyValue(empID))
                        {
                            emp.EntityStatus = Com.Data.EntityStatus.Update;
                        }
                        else
                        {
                            emp.EntityStatus = Com.Data.EntityStatus.New;
                        }
                        emp.SetProperty("EmpID", empID);
                        emp.SetProperty("EmpName", empName);
                        emp.SetProperty("DomainAccount", this.txtADUserID.Text);
                        emp.SetProperty("DeptID", deptID);
                        emp.SetProperty("SyncTime", System.DateTime.Now.ToString());
                        emp.SetProperty("ModDate", System.DateTime.Now.ToString());
                        emp.Save(!this.DataManager.IsBeginTrasaction);

                        string nItemID;
                        if (CheckOutOfOfficeEmpID(empID, out nItemID))
                        {
                            this.itemID = nItemID;
                        }
                        else
                        {
                            string sql = string.Format(@" IF Not Exists (Select EmpID from WF_OutOfOfficeSet Where EmpID='{1}') 
                                                Insert Into WF_OutOfOfficeSet(ItemID,EmpID) Values('{0}','{1}')", this.itemID, empID);
                            this.DataManager.Execute(sql);
                        }

                    }
                    catch
                    {
                        this.AjaxShowMessage("系统中无此用户，请重新输入用户域账号！", true);
                        return;
                    }
                }

                this.DataManager.BeginTransaction();
                SaveData();
                SetOutOfOffice();
                this.DataManager.CommitTransaction();
                //this.AjaxShowMessage(this.udateSubmit, "设置成功！", true);
                this.WindowClose();
            }
            catch (Exception ex)
            {
                this.DataManager.RollbackTransaction();
                //this.AjaxShowMessage(this.udateSubmit, "设置失败！", true);
                CentaUtil.SendExceptionMessage(this.Page, ex);

            }

            Session.Remove("OutOfOfficeSetDataSet");
            //this.AjaxSetWindowReturnValue(this.udateSubmit, "true");
            //this.AjaxWindowClose(this.udateSubmit); 

        }
    }
}